/**
 * @(#)DateConverter.java 2011-10-18
 * 
 * Copyright 2000-2011 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */
package com.szf.base.web;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.szf.util.StringUtil;

/**
 * 将前台输入字符串转换为Date类型
 * 
 * @version 1.0 2011-10-18
 * @since 2.0
 */
@SuppressWarnings("rawtypes")
public class DateConverter extends StrutsTypeConverter {

	private static final String DATE_TIME_FOMART = "yyyy-MM-dd HH:mm:ss";
	private static final String DATE_FOMART = "yyyy-MM-dd";

	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Date date = null;
		String dateString = null;
		if (values != null && values.length > 0) {
			dateString = values[0];
			if (StringUtil.isNotBlank(dateString)) {
				// 尝试 yyyy-MM-dd HH:mm:ss
				SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FOMART);
				try{
					date = format.parse(dateString);
				}catch(ParseException e){
					date = null;
				}
				if (date == null) {
					format = new SimpleDateFormat(DATE_FOMART);
					try {
						date = format.parse(dateString);
					} catch (ParseException e) {
						date = null;
					}
				}
				// 尝试 timstamp
				if (date == null && StringUtil.isNumeric(dateString)) {
					date = new Timestamp(Long.valueOf(dateString));
				}
			}
		}
		return date;
	}

	@Override
	public String convertToString(Map context, Object o) {
		// we don't need this ?
		return null;
	}

}
